import { useQuery } from '@umijs/max';
// antd
import { Carousel, Image } from 'antd';
// 公共函数
import '@/utils/adapter.min.js';
import { addCommas } from '@/utils/index';
import { WebRtcStreamer } from '@/utils/webRtcStreamer';
// 组件
// import CustomDatePicker from '@/components/CustomDatePicker';
// import DPlayerComponent from '@/components/DPlayerComponent';
import { MenuList } from '@/components/MenuList/menuList';
// 公共图表组件
import { BarChartBaseValue } from '@/components/Echarts/BarChartBaseValue';
import { BarChartTopFive } from '@/components/Echarts/BarChartTopFive';
import { LineChartBaseValue } from '@/components/Echarts/LineChartBaseValue';
import { PieChartProportion } from '@/components/Echarts/PieChartProportion';
// 页面图表组件
import { BarChart } from './components/barChart'; // 双柱 折柱混合图 双坐标
import { LineChart } from './components/lineChart'; // 折线 双坐标
// 图片 ｜ 视频
import BgLunLeftB2 from '@/assets/images/bg-lun-left-b2.png';
import BgLunRightB2 from '@/assets/images/bg-lun-right-b2.png';
// import videoUrl from '@/assets/video/video.mp4';
// 接口地址
import { ApiUrl } from '@/services/data-board/boardOne';
// 接口
import {
  averageDaySupply,
  getBleedingTemperatureMonitor,
  getFishTypeProportion,
  getIpList,
  getPHMonitor,
  getPassRateTrend,
  getRawMaterialFish,
  getRawMaterialFishTopFive,
  getTempTemperatureMonitor,
} from '@/services/data-board/boardOne';
// import { useEffect } from 'react';
// ts
import type {
  LineMonitorType,
  TopFiveType,
  TrendType,
  proporDataType,
} from '@/components/Echarts/typing';
import type {
  GetPassRateTrendType,
  GetRawMaterialFishTopFiveType,
} from '@/services/data-board/typing';
import type { AverType, BleedType, RawFishSupplyType } from './typing';

// const dateTypes = [
//   {
//     name: '本月',
//     active: true,
//   },
//   {
//     name: '本季',
//     active: false,
//   },
//   {
//     name: '本年',
//     active: false,
//   },
// ];

let webRtcServer = null;

export default function DataBoardOne() {
  // 获取视频ip地址
  const { data: ipData, isSuccess: ipIsSuccess } = useQuery({
    queryKey: ['getIpList'],
    queryFn: () => getIpList({ type: 1 }),
    refetchInterval: false,
  });
  console.log('ipIsSuccess', ipIsSuccess);
  if (ipIsSuccess) {
    const { resultData } = ipData;
    const ipAddress = resultData[0].ipAddress;
    console.log('ipAddress', ipAddress);
    const IpPath = process.env.VIDEO_URL ? process.env.VIDEO_URL : '';
    webRtcServer = new WebRtcStreamer('video1', IpPath);
    // webRtcServer.connect('rtsp://admin:zhuhai12@192.168.1.107', '', '', '');
    webRtcServer.connect(`rtsp://admin:zhuhai12@${ipAddress}`, '', '', '');
  }

  // 图1 数据 -----
  let rawFishSupplyData: RawFishSupplyType.StateType = {
    xAxisData: [],
    seriesData: [],
  };
  // 图1 原料鱼供应量
  const { data: rawFishData, isSuccess: rawFishIsSuccess } = useQuery({
    queryKey: [ApiUrl.GETRAWMATERIALFISH],
    queryFn: () => getRawMaterialFish({}),
  });

  if (rawFishIsSuccess) {
    const { resultData } = rawFishData;
    rawFishSupplyData = {
      xAxisData: resultData[0].value.map((item) => item.date) ?? [],
      seriesData: resultData.map((el) => ({
        name: el.name,
        data: el.value.map((item) => item.value),
      })),
    };
  }

  // 图2 数据
  let bleedData: BleedType.StateType = {
    xAxisData: [],
    seriesData1: [],
    seriesData2: [],
  };
  // 图2-1 放血池温度监控
  const { data: bleedingData, isSuccess: bleedingIsSuccess } = useQuery({
    queryKey: [ApiUrl.GETBLEEDINGTEMPERATUREMONITOR],
    queryFn: () => getBleedingTemperatureMonitor({}),
  });

  if (bleedingIsSuccess) {
    const { resultData } = bleedingData;
    bleedData.xAxisData = resultData[0].value.map((item) => item.time) ?? [];
    bleedData.seriesData1 = resultData.map((el) => ({
      name: el.name,
      data: el.value.map((item) => item.value),
    }));
  }
  // 图2-2 暂养池温度监控
  const { data: tempData, isSuccess: tempIsSuccess } = useQuery({
    queryKey: [ApiUrl.GETTEMPTEMPERATUREMONITOR],
    queryFn: () => getTempTemperatureMonitor({}),
  });

  if (tempIsSuccess) {
    // console.log('tempData', tempData, temData);
    const { resultData } = tempData;
    bleedData.seriesData2 = resultData.map((el) => ({
      name: el.name,
      data: el.value.map((item) => item.value),
    }));
  }

  // 图3 数据
  let phMonData: LineMonitorType.StateType = {
    xAxisData: [],
    seriesData: [],
  };
  // 图3 放血池PH值监控
  const { data: phMonitorData, isSuccess: phMonitorIsSuccess } = useQuery({
    queryKey: [ApiUrl.GETPHMONITOR],
    queryFn: () => getPHMonitor({}),
  });

  if (phMonitorIsSuccess) {
    const { resultData } = phMonitorData;
    phMonData = {
      xAxisData: resultData[0].value.map((item) => item.time) ?? [],
      seriesData: resultData.map((el) => ({
        name: el.name,
        data: el.value.map((item) => item.value),
      })),
    };
  }

  // 图4 数据 -----
  let passRateTrendData: TrendType.StateType = {
    xAxisData: [],
    seriesData: [],
  };
  // 图4 合格率趋势
  const { data: passRateData, isSuccess: passRateIsSuccess } = useQuery({
    queryKey: [ApiUrl.GETPASSRATETREND],
    queryFn: () => getPassRateTrend({}),
  });

  if (passRateIsSuccess) {
    const resultData =
      passRateData?.resultData as GetPassRateTrendType.Response;
    const { lowerLimit = [], reality = [] } = resultData;
    passRateTrendData = {
      xAxisData: lowerLimit.map((item) => item.date) ?? [],
      seriesData: [
        lowerLimit.map((item) => item.value) ?? [],
        reality.map((item) => item.value) ?? [],
      ],
    };
  }

  // 图5 数据
  let proporData: proporDataType.StateType = {
    seriesData: [],
  };
  // 图5 加工鱼类占比
  const { data: proportionData, isSuccess: proportionIsSuccess } = useQuery({
    queryKey: [ApiUrl.GETFISHTYPEPROPORTION],
    queryFn: () => getFishTypeProportion({}),
  });

  if (proportionIsSuccess) {
    const { resultData } = proportionData;
    proporData = {
      seriesData: resultData[0].data,
    };
  }

  // 图6 数据
  let fishTopData: TopFiveType.StateType = {
    xAxisData: [],
    seriesData: [],
  };
  // 图6 原料鱼累计供应Top5
  const { data: fishTop5Data, isSuccess: fishTop5IsSuccess } = useQuery({
    queryKey: [ApiUrl.GETRAWMATERIALFISHTOPFIVE],
    queryFn: () => getRawMaterialFishTopFive({}),
  });

  if (fishTop5IsSuccess) {
    const { resultData } = fishTop5Data;
    let newResultData: GetRawMaterialFishTopFiveType.Value[] = [];
    resultData.forEach((el) => {
      newResultData.push({
        name: el.name,
        value: el.value.reduce((total, curr) => total + +curr.value, 0),
      });
    });
    // 辅助背景值
    const fData: number[] = [];
    const maxVal = newResultData.reduce((total, cur) => total + +cur.value, 0);
    newResultData.forEach(() => {
      fData.push(maxVal);
    });
    fishTopData = {
      xAxisData:
        newResultData
          .map((item, index) => `TOP${index + 1} ${item.name}`)
          .reverse() ?? [],
      seriesData: [
        newResultData.map((el) => el.value).reverse(),
        fData.reverse(),
      ],
    };
  }

  // 鱼塘信息
  const { data: averageData, isSuccess: averageIsSuccess } = useQuery({
    queryKey: [ApiUrl.AVERAGEDAYSUPPLY],
    queryFn: () => averageDaySupply({}),
  });
  let averData = averageData?.resultData as AverType.data[];

  return (
    <div className="main-wrapper">
      {/* ---------- 左 ---------- */}
      <div className="main main-left">
        {/* box */}
        <div className="main-box">
          <div className="main-box-header">
            <div className="header-font">原料鱼供应量</div>
            {/* <CustomDatePicker picker="year"></CustomDatePicker> */}
          </div>
          <div className="main-box-contain">
            {/* chart */}
            <BarChart rawFishSupplyData={rawFishSupplyData} />
          </div>
        </div>
        {/* box */}
        <div className="main-box">
          <div className="main-box-header">
            <div className="header-font">温度监控</div>
            {/* <CustomDatePicker picker="date"></CustomDatePicker> */}
          </div>
          <div className="main-box-contain">
            {/* chart */}
            <LineChart bleedData={bleedData} />
          </div>
        </div>
        {/* box */}
        <div className="main-box">
          <div className="main-box-header">
            <div className="header-font">PH值监控</div>
            {/* <CustomDatePicker picker="date"></CustomDatePicker> */}
          </div>
          <div className="main-box-contain">
            {/* chart */}
            <LineChartBaseValue monitorData={phMonData} />
          </div>
        </div>
      </div>
      {/* ---------- 中 ---------- */}
      <div className="main main-center">
        {/* 菜单 */}
        <div className="main-center-menu">
          {averageIsSuccess ? (
            <MenuList
              list={[
                {
                  name: `${averData[0].name}日均供应量`,
                  num: addCommas(averData[0].value),
                  unit: '千克',
                },
                {
                  name: `${averData[1].name}日均供应量`,
                  num: addCommas(averData[1].value),
                  unit: '千克',
                },
                {
                  name: averData[2].name,
                  num: addCommas(averData[2].value),
                  unit: '个',
                },
              ]}
            />
          ) : null}
        </div>

        {/* 视频 */}
        <div className="main-center-video">
          {/* <DPlayerComponent url={videoUrl} /> */}
          <video
            muted
            autoPlay
            id="video1"
            style={{ width: '100%', height: '100%', objectFit: 'fill' }}
          >
            您的浏览器不支持 video 标签。
          </video>
        </div>
        {/* 走马灯 */}
        <div className="main-center-lunbo">
          {/* autoplay */}
          <Carousel dots>
            <div className="slide">
              <div className="slide-left">
                <div className="slide-left-img-box">
                  <Image
                    preview={false}
                    className="slide-left-img"
                    src={BgLunLeftB2}
                  ></Image>
                </div>
                <div className="slide-left-font-box">集元水产</div>
              </div>
              <div className="sldie-right">
                <h5>公司简介</h5>
                <p>
                  珠海市农业龙头企业，广东省高新技术企业，并取得多项成果专利。公司一直以来专注于水产品养殖、加工、市场开发营销；并在水质治理、生物技术开发运用，健康养殖技术推广、土壤修复等领域开拓发展。现在＂鲜城故事”品牌系列水产品已经在全国各地布局强大的销售网络，产品质量深受广大消费者的赞誉和信赖，并得到中央电视台财经频道和广东卫视的多次专题采访报道。
                </p>
                <p>
                  公司产品在2018年、2019年连续获得广东省名牌产品，2020年广东省“粤字号”入库品牌，广东省十强鲜活水产经营企业，最受欢迎的渔业食材供应商，珠海首届十大品牌农产品，2019最具品牌影响力奖，2019年2020年连续获得最佳产品奖。公司是“连续多年广东省守合同重信用企业”，在全国享有较高的声誉，是珠海地区最大的水产品及海鲈鱼加工企业之一。
                </p>
              </div>
            </div>
            <div className="slide">
              <div className="slide-left">
                <div className="slide-left-img-box1">
                  <Image
                    preview={false}
                    className="slide-left-img1"
                    src={BgLunRightB2}
                  ></Image>
                </div>
                <div className="slide-left-font-box1">格力预制菜装备</div>
              </div>
              <div className="sldie-right">
                <h5>格力预制菜装备</h5>
                <p>
                  2022年，格力电器牵头成立广东省预制菜装备产业发展联合会，目前会员单位已有40余家。广东省预制菜装备产业发展联合会以“成为全球领先的预制菜装备产业发展促进组织”为愿景，秉持着“开放、多元、融合、共赢、创新、发展”的价值观，坚持自主创新，绿色发展通过信息共享、技术共享、资源共享，实现产业优势互补，打造具有核心竞争力的预制菜装备产业集群，带动传统农业工业化升级，促进乡村经济兴，满足人民群众对美好生活的向往。
                </p>
              </div>
            </div>
          </Carousel>
        </div>
      </div>
      {/* ---------- 右 ---------- */}
      <div className="main main-right">
        {/* box */}
        <div className="main-box">
          <div className="main-box-header">
            <div className="header-font">合格率趋势</div>
            {/* <CustomDatePicker picker="month"></CustomDatePicker> */}
          </div>
          <div className="main-box-contain">
            {/* chart */}
            <BarChartBaseValue trendData={passRateTrendData} />
          </div>
        </div>
        {/* box */}
        <div className="main-box">
          <div className="main-box-header">
            <div className="header-font">加工鱼类占比</div>
            {/* <CustomDatePicker picker="month"></CustomDatePicker> */}
          </div>
          <div className="main-box-contain">
            {/* chart */}
            <PieChartProportion proporData={proporData} />
          </div>
        </div>
        {/* box */}
        <div className="main-box">
          <div className="main-box-header">
            <div className="header-font">原料鱼累计供应TOP5</div>
            {/* <div className="header-font header-font-type">
              {dateTypes.map((item) => (
                <span className="type" key={item.name}>
                  {item.name}
                </span>
              ))}
            </div> */}
          </div>
          <div className="main-box-contain">
            {/* chart */}
            <BarChartTopFive TopFiveData={fishTopData} />
          </div>
        </div>
      </div>
    </div>
  );
}
